<template>
    <div class="app-container">
        <span style="font-size: 26px;margin-right: 100px;">高蛋白大豆补贴</span>
        <el-button v-if="!formDisabled" type="primary" size="medium" :loading="saveLoading" @click="saveForm">保存</el-button>
        <el-button v-if="!formDisabled && !abnormalDisabled" type="primary" plain size="medium" :loading="submitLoading"
            @click="submitForm">下一个</el-button>
        <el-button v-if="formDisabled" disabled type="info" size="medium">审核中</el-button>

        <el-button @click="exportInfo" style="float:right" type="success" plain size="medium">导出</el-button>

        <el-form ref="elForm" :disabled="formDisabled" :model="form" :rules="rules" size="medium" label-width="400px"
            label-position="left">
            <div class="card-container">
                <el-card class="infoDiv">
                    <span class="corner-label">基本信息</span>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="申报补贴农民(职工、新型经营主体负责人)身份证" prop="idCard">
                                <el-input v-model="form.idCard" @blur="syncHistory" :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="申报补贴农民(职工、新型经营主体负责人)姓名" prop="appyBy">
                                <el-input v-model="form.appyBy" :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="申报补贴农民(职工、新型经营主体负责人)联系电话" prop="phone">
                                <el-input v-model="form.phone" :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="身份证地址" prop="idCardAddr">
                                <el-input v-model="form.idCardAddr" @blur="syncOftenAddrIfNotModified"
                                    :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="现住地址" prop="oftenAddr">
                                <el-input v-model="form.oftenAddr" :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="申报补贴农民(职工、新型经营主体负责人)一卡通账号" prop="bankCard">
                                <el-input v-model="form.bankCard" :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <div class="card-container">
                <el-card class="infoDiv">
                    <span class="corner-label">申报面积</span>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="自有耕地种植大豆面积(亩)" prop="ownArea">
                                <el-input v-model="form.ownArea" type="number" :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 动态行：使用 v-for 渲染每一条 -->
                    <el-row :gutter="16" v-for="(item, index) in form.borrow" :key="index"
                        style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="6">
                            <el-form-item label="承租他人姓名" :prop="'borrow.' + index + '.borrowName'" label-width="100px">
                                <el-input v-model="item.borrowName" placeholder="请输入" clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9">
                            <el-form-item label="承租他人耕地种植大豆面积(亩)" :prop="'borrow.' + index + '.borrowArea'"
                                label-width="220px">
                                <el-input v-model="item.borrowArea" placeholder="请输入" type="number" show-word-limit
                                    clearable :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="承租他人联系电话" :prop="'borrow.' + index + '.borrowPhone'" label-width="130px">
                                <el-input v-model="item.borrowPhone" placeholder="请输入" show-word-limit clearable
                                    :style="{ width: '100%' }">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2" v-if="form.borrow.length > 1">
                            <el-button type="danger" icon="el-icon-delete" circle @click="removeBorrow(index)"></el-button>
                        </el-col>
                    </el-row>

                    <!-- 添加按钮 -->
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-button @click="addBorrow" type="primary" plain size="medium">
                                添加承租他人信息
                            </el-button>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="承租他人耕地种植大豆面积(亩)" prop="borrowAmount">
                                <el-input v-model="form.borrowAmount" style="width: 80%" disabled>
                                    <template slot="append">（合计）</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item :label="`申报补贴农民(职工、新型经营主体)${year}年种植大豆面积(亩)`" prop="gaodanbaiArea">
                                <el-input v-model="form.gaodanbaiArea" :style="{ width: '80%' }" disabled><template
                                        slot="append">（合计）</template></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <div class="card-container">
                <el-card class="infoDiv">
                    <span class="corner-label">其他情况</span>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label-width="420px" :label="`${curyear}年10月1日-${year}年6月30日前购买高蛋白大豆品种名称`"
                                prop="gaodanbaiType">
                                <el-select v-model="form.gaodanbaiType" :remote-method="remoteQueryDadouTypes"
                                    :loading="loading" filterable remote reserve-keyword placeholder="请输入大豆品种名称"
                                    :style="{ width: '80%' }" clearable>
                                    <el-option v-for="item in dadouTypeOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label-width="420px" :label="`${curyear}年10月1日-${year}年6月30日前购买高蛋白大豆种子数量(斤)`"
                                prop="gaodanbaiWeight">
                                <el-input v-model="form.gaodanbaiWeight" type="number" :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label-width="420px" :label="`${year}年种植高蛋白大豆面积(亩)(品种粗蛋白含量≥43.0%)`"
                                prop="areaAmountdouGaodanbai">
                                <el-input v-model="form.areaAmountdouGaodanbai" type="number"
                                    :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label-width="420px" label="在何处购买的高蛋白大豆种子(填写具体名称)" prop="gaodanbaiWhere">
                                <el-input v-model="form.gaodanbaiWhere" :style="{ width: '80%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-card>
            </div>
            <div class="card-container">
                <el-card class="infoDiv">
                    <span class="corner-label">附件上传</span>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="12">
                            <el-form-item label-width="220px" label="高蛋白大豆补贴申请表" prop="appyExcel">
                                <el-upload class="upload-demo" action="http://111.40.188.220:9060/subsidy/file/upload"
                                    :on-preview="handlePreview" :on-remove="(file) => handleRemove(file, 'appyExcel')"
                                    :on-success="(response, file) => handleSuccess(response, file, 'appyExcel')" :limit="1"
                                    :on-exceed="handleExceed" :file-list="uploadedAppyExcel">
                                    <el-button icon="el-icon-upload" plain type="primary">上传附件</el-button>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <span style="color:gray">支持.png.jpg.pdf 等格式，单个附件不得超过512M</span>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="12">
                            <el-form-item label-width="220px" label="销售凭证" prop="saleFile">
                                <el-upload class="upload-demo" action="http://111.40.188.220:9060/subsidy/file/upload"
                                    :on-preview="handlePreview" :on-remove="(file) => handleRemove(file, 'saleFile')"
                                    :on-success="(response, file) => handleSuccess(response, file, 'saleFile')" :limit="1"
                                    :on-exceed="handleExceed" :file-list="uploadedSaleFile">
                                    <el-button icon="el-icon-upload" plain type="primary">上传附件</el-button>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <span style="color:gray">支持.png.jpg.pdf 等格式，单个附件不得超过512M</span>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <div class="card-container">
                <el-card class="infoDiv">
                    <span class="corner-label">村级负责人信息</span>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label-width="200px" label="村级负责人" prop="chargeName">
                                <el-input v-model="form.chargeName" :style="{ width: '40%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label-width="200px" label="负责人职务" prop="chargePost">
                                <el-input v-model="form.chargePost" :style="{ width: '40%' }"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label-width="200px" label="负责人电话" prop="chargePhone">
                                <el-input v-model="form.chargePhone" :style="{ width: '40%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <!-- 对于异常情况，驳回理由的显示 -->
            <div class="card-container" v-if="abnormalDisabled">
                <el-card class="infoDiv">
                    <span class="corner-label" style="background-color:rgb(234, 183, 225)">驳回理由</span>
                    <el-row :gutter="12" style="margin-bottom: 10px; margin-top: 10px;">
                        <el-col :span="24">
                            <el-form-item label="驳回理由" prop="abnormal" label-width="80px">
                                <el-input :disabled="true" v-model="form.abnormal" type="textarea"
                                    :autosize="{ minRows: 4, maxRows: 8 }" :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
        </el-form>
    </div>
</template>
<script>
import { queryhistoryOne, addProduce, updateProduce, queryDadouType, queryCunCharge, submitProduce, getProduceByappNum, getProduceById, rejectProduce } from "@/api/agriculture/agriculture";
import * as XLSX from 'xlsx';

export default {
    name: "prosoy",
    data() {
        const now = new Date();
        return {
            dadouTypeOptions: [], // 下拉选项
            loading: false,    // 加载状态

            // 按钮loading
            saveLoading: false,
            submitLoading: false,

            formDisabled: false, //控制整个表格是否输入
            abnormalDisabled: false, //控制驳回表格是否显示
            rejectDisabled: false, //控制审批窗口是否显示
            isDisabled: true, //控制审批窗口中的驳回理由是否显示

            year: now.getFullYear(),
            curyear: now.getFullYear() - 1,
            uploadedAppyExcel: [], //申请表url存储
            uploadedSaleFile: [], //销售url存储

            form: {
                appyBy: undefined,
                sex: undefined,
                appType: '高蛋白大豆补贴',
                idCard: undefined,
                idCardAddr: undefined,
                oftenAddr: undefined,
                phone: undefined,
                bankCard: undefined,
                remark: undefined,
                ownArea: 0, //自有
                gaodanbaiArea: 0, // 自有和租借他人之和
                // areaAmountdou: 0, //高油和高蛋白面积之和
                borrowAmount: 0, //租借所有亩数
                //其他情况,高蛋白
                gaodanbaiType: undefined,
                gaodanbaiWeight: undefined,
                areaAmountdouGaodanbai: undefined,
                gaodanbaiWhere: undefined,
                //负责人
                chargeName: undefined,
                chargePhone: undefined,
                chargePost: undefined,
                //附件
                appyExcel: undefined,
                saleFile: undefined,
                //租借：他人
                borrow: [{
                    borrowName: undefined,
                    borrowArea: 0,
                    borrowPhone: undefined,
                }],
                // appNum:1111,
                townName: undefined,
                villageName: undefined,
                submitBy: undefined,
                nodeName: undefined,
                status: '待处理',
                year: new Date().getFullYear(),
            },
            rules: {
                appyBy: [{
                    required: true,
                    message: '请输入申请人',
                    trigger: 'blur'
                }],
                sex: [{
                    required: true,
                    message: '请选择性别',
                    trigger: 'change'
                }],
                idCard: [{
                    required: true,
                    message: '请输入身份证号码',
                    trigger: 'blur'
                }, {
                    pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                    message: '请输入正确的身份证号',
                    trigger: 'blur'
                }],
                bankCard: [{
                    required: true,
                    message: '请输入一卡通账号',
                    trigger: 'blur'
                }],
                appType: [{
                    required: true,
                    message: '请选择补贴类型',
                    trigger: 'change'
                }],
                idCardAddr: [{
                    required: true,
                    message: '请输入身份证地址',
                    trigger: 'blur'
                }],
                oftenAddr: [{
                    required: true,
                    message: '请输入现住地址',
                    trigger: 'blur'
                }],
                phone: [{
                    required: true,
                    message: '请输入联系方式',
                    trigger: 'blur'
                }, {
                    pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                    message: '请输入正确的手机号',
                    trigger: 'blur'
                }],
                chargePhone: [{
                    required: true,
                    message: '请输入联系方式',
                    trigger: 'blur'
                }, {
                    pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                    message: '请输入正确的手机号',
                    trigger: 'blur'
                }],
                chargeName: [{
                    required: true,
                    message: '请输入责任人',
                    trigger: 'blur'
                }],
                chargePost: [{
                    required: true,
                    message: '请输入责任职务',
                    trigger: 'blur'
                }],
                gaodanbaiType: [{
                    required: true,
                    message: '请输入高蛋白大豆品种',
                    trigger: 'blur'
                }],

                gaodanbaiWeight: [{
                    required: true,
                    message: '请输入购买高蛋白大豆种子重量',
                    trigger: 'blur'
                }],

                areaAmountdouGaodanbai: [{
                    required: true,
                    message: '请输入种植高蛋白大豆面积',
                    trigger: 'blur'
                }],
                gaodanbaiWhere: [{
                    required: true,
                    message: '请输入在哪购买高蛋白大豆',
                    trigger: 'blur'
                }],

                remark: [],
            },
            sexOptions: [{
                "label": "男",
                "value": "男"
            }, {
                "label": "女",
                "value": "女"
            }]
        }
    },

    computed: {
        totalBorrowArea() {
            // 假设保留 2 位小数 → 放大 100 倍 → 计算完再缩小
            const sum = this.form.borrow.reduce((acc, item) => {
                const value = Number(item.borrowArea) || 0;
                // 放大 100 倍 → 变成整数运算
                return acc + Math.round(value * 10000);
            }, 0);

            // 缩小 100 倍，保留 2 位小数
            return (sum / 10000);
        },
        //合计
        computedTotalArea() {
            const ownArea = this.form.ownArea;
            const borrow = this.totalBorrowArea;
            var m = Math.pow(100, 2);
            const hehe = (ownArea * m + borrow * m) / m;
            return hehe;
        }
    },
    watch: {
        // 监听计算结果，同步回 form（用于显示）
        totalBorrowArea(newVal) {
            this.form.borrowAmount = newVal;
        },
        computedTotalArea(newVal) {
            this.form.gaodanbaiArea = newVal;
        },
        'form.oftenAddr'(newValue, oldValue) {
            // 注意：要防止初始同步或 blur 同步触发此 watcher 时错误地设置标记
            // 我们只关心用户主动输入导致的变化
            if (oldValue !== undefined && newValue !== oldValue) {
                // 用户修改了现住地址，标记为已自定义
                this.hasUserModifiedOftenAddr = true;
            }
        },
        '$route'(to, from) {
            const id = to.params.id;
            if (id) {
                this.fetchData(id);
            }
        }
    },
    created() {

        if (this.$store.state.user.roles[0] == 'village') {  // 为村干部时
            this.villageName = this.$store.state.user.user.villageName;
            this.townName = this.$store.state.user.user.townName;
            this.form.nodeName = this.villageName
            this.form.villageName = this.villageName
            this.form.submitBy = this.villageName
            this.form.townName = this.townName
        }
        const year = new Date().getFullYear();
        queryCunCharge({ year: year, villageName: this.villageName }).then(res => {
            this.form.chargeName = res.data.chargeName;
            this.form.chargePhone = res.data.chargePhone;
            this.form.chargePost = res.data.chargePost;

        })

        const id = this.$route.params && this.$route.params.id;
        if (id) {
            // console.log("查询工单编号", id)
            getProduceById(id).then(response => {
                console.log("查询信息", response)
                const data = response.data;
                // 判断 borrow 是否为字符串，如果是，尝试解析为数组
                if (data.borrow && typeof data.borrow === 'string') {
                    try {
                        data.borrow = JSON.parse(data.borrow);
                    } catch (error) {
                        console.warn('解析 borrow 字段失败，使用空数组', error);
                        data.borrow = []; // 解析失败时给默认值
                    }
                } else if (!data.borrow) {
                    // 如果 borrow 为 null/undefined，初始化为空数组
                    data.borrow = [];
                }
                this.form = data;
                console.log("form", this.form)
                this.uploadedAppyExcel.push({ name: '申请表', url: this.form.appyExcel })
                this.uploadedSaleFile.push({ name: '销售凭证', url: this.form.saleFile });

                if (this.form.node > 1) {
                    this.formDisabled = 'true'
                }
                if (this.form.node == 1 && this.form.status == '异常') {
                    this.abnormalDisabled = 'true'
                }
            });
        }
    },
    methods: {
        fetchData(id) {
            console.log("查询工单编号:", id);
            getProduceById(id).then(response => {
                console.log("查询信息", response)
                const data = response.data;
                // 判断 borrow 是否为字符串，如果是，尝试解析为数组
                if (data.borrow && typeof data.borrow === 'string') {
                    try {
                        data.borrow = JSON.parse(data.borrow);
                    } catch (error) {
                        console.warn('解析 borrow 字段失败，使用空数组', error);
                        data.borrow = []; // 解析失败时给默认值
                    }
                } else if (!data.borrow) {
                    // 如果 borrow 为 null/undefined，初始化为空数组
                    data.borrow = [];
                }
                this.form = data;
                console.log("form", this.form)
                this.uploadedAppyExcel.push({ name: '申请表', url: this.form.appyExcel })
                this.uploadedSaleFile.push({ name: '销售凭证', url: this.form.saleFile });

                if (this.form.node > 1) {
                    this.formDisabled = 'true'
                }
                if (this.form.node == 1 && this.form.status == '异常') {
                    this.abnormalDisabled = 'true'
                }
            });
        },
        async remoteQueryDadouTypes(queryString) {
            // 清空时不需要请求
            if (!queryString || !queryString.trim()) {
                this.dadouTypeOptions = [];
                return;
            }

            this.loading = true;

            try {
                const response = await queryDadouType({ gaodanbaiType: queryString.trim() });
                console.log("dadou", response)
                const result = response; // 假设返回的是字符串数组：["黑豆1号", "黑豆2号"]

                if (Array.isArray(result)) {
                    // 转为 el-option 所需格式：{ value, label }
                    this.dadouTypeOptions = result.map((name, index) => ({
                        value: name,
                        label: name
                    }));

                } else {
                    this.dadouTypeOptions = [];
                }
            } catch (error) {
                console.error('查询大豆品种失败：', error);
                this.dadouTypeOptions = [];
            } finally {
                this.loading = false;
            }
        },
        syncOftenAddrIfNotModified() {
            const idCardAddr = this.form.idCardAddr.trim();
            // 只有在用户没有手动修改过 oftenAddr 的情况下才进行同步
            if (!this.hasUserModifiedOftenAddr && idCardAddr) {
                this.form.oftenAddr = idCardAddr;
            }
            // 如果身份证地址为空，也可以选择清空 oftenAddr（可选）
            // else if (!this.hasUserModifiedOftenAddr) {
            //   this.form.oftenAddr = '';
            // }
        },
        syncHistory() {
            const idCard = this.form.idCard;
            queryhistoryOne({ idCard: idCard }).then(res => {
                console.log("历史信息", res);
                if (res.idCard) {
                    this.form.appyBy = res.appyBy;
                    this.form.phone = res.phone;
                    this.form.idCardAddr = res.idCardAddr;
                    this.form.oftenAddr = res.oftenAddr;
                    this.form.bankCard = res.bankCard;
                }

            })
        },

        handleSuccess(response, file, formFieldName) {
            console.log('上传成功:', response, file);
            if (response && response.code === 200) {
                const filePath = response.data.filePath;
                if (filePath) {
                    this.form[formFieldName] = filePath; // 将 ossId 保存到表单字段
                    this.$message.success('上传成功，已保存文件ID');
                    console.log('上传情况', this.form)

                } else {
                    this.$message.error('上传成功，但未返回 ossId');
                }
            } else {
                this.$message.error('上传失败，服务器返回错误');
            }
        },
        handlePreview(file) {
            const serveIpPort = "111.40.188.220";
            let originalUrl = '';
            if (Object.keys(file).includes('url')) {
                originalUrl = file.url;
            } else {
                originalUrl = file.response.data.filePath;
            }

            const fileUrl = originalUrl.replace(/http:\/\/[\d.]+/, `http://${serveIpPort}`);
            window.open(fileUrl);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，请删除现有文件后再选择新文件！`);
        },
        handleRemove(file, formFieldName) {
            delFile(file.response.data.ossId).then(response => {
                this.$message.success('删除成功');
                this.form[formFieldName] = undefined;
                console.log("保存的数据", this.form)
            }).catch(error => {
                this.$message.error('删除失败' + (error.message || '未知错误'));
            });
        },
        //导出excel
        exportInfo() {
            const filePath = '/excel/personGaodanbai.xlsx'; // public 目录下的 Excel 文件路径
            // 使用 fetch 从 public 目录加载文件
            fetch(filePath)
                .then(response => response.arrayBuffer()) // 获取文件内容的 ArrayBuffer
                .then(data => {
                    const wb = XLSX.read(data, { type: 'buffer' });

                    // 获取第一个工作表
                    const ws = wb.Sheets[wb.SheetNames[0]];

                    // 获取工作表的所有数据（不丢失原始样式）
                    const wsData = XLSX.utils.sheet_to_json(ws, { header: 1 });

                    // 获取合并单元格的区域
                    const merges = ws['!merges'] || [];

                    // 获取行高和列宽
                    const rowHeights = ws['!rows'] || [];
                    const colWidths = ws['!cols'] || [];

                    // 将新数据添加到工作表数据中
                    this.form.borrow.forEach((item, index) => {
                        if (index < 7) {
                            if (index === 0) {
                                wsData[5 + index] = [
                                    this.form.appyBy,
                                    this.form.gaodanbaiArea,
                                    this.form.ownArea,
                                    this.form.borrowAmount,
                                    item.borrowName,
                                    item.borrowArea,
                                    item.borrowPhone,
                                    this.form.gaodanbaiType,
                                    this.form.gaodanbaiWeight,
                                    this.form.areaAmountdouGaodanbai,
                                    this.form.gaodanbaiWhere,
                                    this.form.phone,
                                    this.form.idCard
                                ];
                            } else {
                                wsData[5 + index] = ['', '', '', '', '', item.borrowName, item.borrowArea, item.borrowPhone, '', '', '', '', '', ''];
                            }
                        } else {
                            wsData.splice(5 + index, 0, ['', '', '', '', '', item.borrowName, item.borrowArea, item.borrowPhone, '', '', '', '', '', '']);
                        }
                    });
                    console.log("最终的数据", wsData);
                    // 将修改后的数据重新写回工作表
                    const newWs = XLSX.utils.aoa_to_sheet(wsData);

                    // 保留合并单元格区域
                    newWs['!merges'] = merges;
                    for (const cell in ws) {
                        if (cell[0] === '!' || !newWs[cell]) continue; // 跳过非单元格或 newWs 中不存在的
                        if (ws[cell] && ws[cell].s) {
                            if (!newWs[cell].s) newWs[cell].s = {};
                            Object.assign(newWs[cell].s, ws[cell].s); // 合并样式
                        }
                        // 可选：保留字体、对齐等
                    }
                    // 保留行高和列宽
                    newWs['!rows'] = rowHeights;
                    newWs['!cols'] = colWidths;

                    // ✅ 关键：必须把新工作表写回工作簿
                    wb.Sheets[wb.SheetNames[0]] = newWs;

                    // 导出修改后的文件
                    const filename = '高蛋白大豆申请表.xlsx'; // 使用 .xlsx 格式
                    XLSX.writeFile(wb, filename);

                    this.message = `文件已导出: ${filename}`;
                })
                .catch(error => {
                    console.error('文件加载失败:', error);
                    this.message = '加载 Excel 文件失败';
                });
        },


        //添加租借人信息
        addBorrow() {
            this.form.borrow.push({
                borrowName: undefined,
                borrowArea: 0,
                borrowPhone: undefined
            });
        },
        removeBorrow(index) {
            if (this.form.borrow.length <= 1) {
                this.$message.warning('至少保留一条信息');
                return;
            }
            this.form.borrow.splice(index, 1);
        },
        getFormattedDateTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        saveForm: function () {
            this.$refs['elForm'].validate(valid => {
                if (valid) {
                    if (this.form.id) {
                        this.saveLoading = true;
                        this.form.status = "待处理";
                        const submitData = { ...this.form };
                        submitData.borrow = JSON.stringify(submitData.borrow);
                        updateProduce(submitData).then(response => {
                            this.$modal.msgSuccess("修改数据成功");
                        }).finally(() => {
                            this.saveLoading = false;
                            this.resetForm();
                            this.$router.push("/agricultureProcess");
                        });
                    } else {
                        this.saveLoading = true;
                        //租借人数组转string
                        const submitData = { ...this.form };
                        submitData.borrow = JSON.stringify(submitData.borrow);
                        addProduce(submitData).then(response => {
                            this.$modal.msgSuccess("新增成功");
                        }).finally(() => {
                            this.saveLoading = false;
                            this.resetForm();
                            this.$router.push("/agricultureProcess");
                        });
                    }
                }
            })
        },

        submitForm: function () {
            this.$refs['elForm'].validate(valid => {
                if (valid) {
                    if (this.form.id) {
                        this.submitLoading = true;
                        this.form.status = "待处理";
                        const submitData = { ...this.form };
                        submitData.borrow = JSON.stringify(submitData.borrow);
                        updateProduce(submitData).then(response => {
                            this.$modal.msgSuccess("修改数据成功");
                        }).finally(() => {
                            this.submitLoading = false;
                            this.resetForm();
                        });
                    } else {
                        this.submitLoading = true;
                        const submitData = { ...this.form };
                        submitData.borrow = JSON.stringify(submitData.borrow);
                        addProduce(submitData).then(response => {
                            this.$modal.msgSuccess("新增成功");
                        }).finally(() => {
                            this.submitLoading = false;
                            this.resetForm();
                        });
                    }

                }
            })
        },
        resetForm() {
            this.$refs['elForm'].resetFields()
        },
    }
}
</script>
<style scoped>
.app-container {
    width: 80%;
    align-items: center;
    margin-left: 10%;

    /* border: 1px solid rgb(204, 28, 28); */
}

.card-container {
    position: relative;
}

.infoDiv {
    width: 100%;
    align-items: center;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;
    padding-top: 20px;
}

.corner-label {
    position: absolute;
    top: 0;
    left: 0;
    background: #81B337;
    /* 背景色 */
    color: white;
    /* 文字颜色 */
    padding: 2px 8px;
    /* 内边距 */
    font-size: 20px;
    /* 字体大小 */
    border-radius: 4px;
    /* 圆角，左上角和右下角有圆角（根据需求调整） */
    transform: translate(-10%, -10%);
    /* 微调位置，使其覆盖在圆角上 */
    /* 如果需要，可以设置z-index */
    z-index: 1;
}
</style>